<?php

namespace app\api\model;
use app\service\UserLevel;
use think\Db;

class YaoqingRecords extends Common
{
    static public function index($user_id, $to_user, $money, $remark, $type = 0, $order_id = '', $data = 0, $update = 0, $show_money = 0, $source_uid = 0)
    {
        $money = round($money, 2);

        if ($money > 0) {
            $balance = Db::name('user')->where(['id' => $user_id])->value('score');
            $current_balance = $data ? ($balance - $money) : ($balance + $money);
            
            if ($current_balance < 0) {
                return false;
            }
            
            if ($data) {
                Db::name('user')->where(['id' => $user_id])->setDec('score', $money);
            } else {
                Db::name('user')->where(['id' => $user_id])->setInc('shouyi', $money);
                Db::name('user')->where(['id' => $user_id])->setInc('score', $money);

                if (stripos($remark, '收益') && stripos($remark, '充值') === false) {
                    // 用户业绩统计
                    self::createData($user_id, $money, 'income');
                }
            }
            
            Db::name('yaoqing_records')->insert([
                'uid'        => $user_id,
                'touid'      => $to_user,
                'content'    => $remark,
                'money'      => $show_money ?: $money,
                'type'       => $type,
                'data'       => $data,
                'order_id'   => $order_id,
                'balance'    => $current_balance,
                'time'       => time(),
                'show_money' => $show_money ?: $money,
                'source_uid' => $source_uid,
            ]);
            
            UserLevel::checkUserLevel($user_id);
            return true;
        }
        
        return false;
    }
    
    /**
     * 用户业绩统计
     */
    static public function createData($user_id, $money, $type)
    {
        // 实现用户业绩统计逻辑
        // ...
    }
}
